﻿using System;
using System.IO;
using System.IO.IsolatedStorage;
using System.Net;
using System.Reflection;
using System.Security;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Silverlight.Testing;
using Microsoft.Silverlight.Testing.UnitTesting.Metadata.VisualStudio;
using Microsoft.VisualStudio.TestTools.UnitTesting;


namespace RStein.Posterous.API.Test
{
    /// <summary>
    /// Summary description for UnitTest1
    /// </summary>
    [TestClass]
    public class PosterouAsyncTests : SilverlightTest
    {
        public const string SITE_TAG = "Počítače";
        public PosterouAsyncTests()
        {
           
           //
            // TODO: Add constructor logic here
            //
        }


        private TestContext testContextInstance;
        private IPosterousAccount m_account;
        private ITwitterAccount m_twitterAccount;
        private const string MEDIA_PATH = @"c:\Users\STEIN\Documents\Authortest.jpg";

        /// <summary>
        ///Gets or sets the test context which provides
        ///information about and functionality for the current test run.
        ///</summary>
        public TestContext TestContext
        {
            get
            {
                return testContextInstance;
            }
            set
            {
                testContextInstance = value;
            }
        }

        #region Additional test attributes
        //
        // You can use the following additional attributes as you write your tests:
        //

        [ClassInitialize()]
        public static void MyClassInitialize(TestContext testContext)
        {
        }
        //
        //Use ClassCleanup to run code after all tests in a class have run
        //[ClassCleanup()]
        // public static void MyClassCleanup() { }
        //
        // Use TestInitialize to run code before running each test 
        [TestInitialize()]
        public void MyTestInitialize()
        {
                        
            m_account = PosterousApplication.Current.GetPosterousAccount("stein@tiscali.cz", "xxx");
            m_twitterAccount = PosterousApplication.Current.GetTwitterAccount("rstest2", "xxxx");
        }
        //
        // Use TestCleanup to run code after each test has run
        [TestCleanup()]
        public void MyTestCleanup()
        {          
        }
        //
        #endregion

         [TestMethod]
        [AsynchronousAttribute]
        public void Assert_Download_Sites_OK()
        {
             m_account.SitesLoaded += (o, e) =>
                                          {
                                              Assert.IsFalse(m_account.Sites.Count() == 0);
                                              TestComplete();
                                          };
             m_account.LoadSitesAsync();
                         
            
        }

        [TestMethod] 
        [AsynchronousAttribute]
        public void Assert_Secondary_Sites_OK()
        {

            m_account.SitesLoaded += (o, e) =>
                                         {
                                             IPosterousSite site = getSecondarySite();
                                             site.TagsLoaded += (_, __) =>
                                                                    {
                                                                        Assert.IsTrue(site.IsTagsLoaded);
                                                                        TestComplete();
                                                                    };
                                             site.LoadTagsAsync();
                                         };
            m_account.LoadSitesAsync();            
            
            
                        
                        
        }

        [TestMethod] 
        [AsynchronousAttribute]
        public void Assert_AddPost_Secondary_Site_OK()
        {

            m_account.SitesLoaded += (o, e) =>
            {
                IPosterousSite site = getSecondarySite();
                IPosterousPost newPost = site.CreatePost(DateTime.Now + " Příliš žluťoučký kůň úpěl ďábelské ódy",
                                             "Příliš žluťoučký kůň úpěl ďábelské ódy", true);

                newPost.AddTag("Všechno a nic");
                newPost.AddTag("C# omnia vincit");
                newPost.SaveChangesCompleted += (_, __) =>
                                                    {
                                                        Assert.IsTrue(newPost.Id > 0);
                                                        TestComplete();
                                                    };
                newPost.SaveChangesAsync();                
                
                
            };

            m_account.LoadSitesAsync();            
            
            
            
        }
        private IPosterousSite getSecondarySite()
        {
            return m_account.Sites.Where(st => !st.IsPrimary).First();
        }

         [TestMethod] 
         [AsynchronousAttribute]
        public void Assert_Auth_Picture_Download_OK()
        {
             m_account.SitesLoaded += (o, e) =>
                                          {
                                              m_account.PrimarySite.LoadAllPostsAsync();
                                              m_account.PrimarySite.PostsLoaded += (_, __) =>
                                                                                       {
                                                                                           m_account.PrimarySite.Posts.First().Author.AuthorPictureLoaded += (_0, _1) =>
                                                                                                                                                                 {
                                                                                                                                                                     Assert.IsFalse(m_account.PrimarySite.Posts.First().Author.AuthorPicture.Length == 0);
                                                                                                                                                                     //using (Stream athFileStream = File.Open(MEDIA_PATH, FileMode.Create, FileAccess.Write))
                                                                                                                                                                     //{
                                                                                                                                                                     //    m_account.PrimarySite.Posts.First().Author.AuthorPicture.CopyToStream(athFileStream);
                                                                                                                                                                     //}
                                                                                                                                                                     TestComplete();

                                                                                                                                                                 };
                                                                                           m_account.PrimarySite.Posts.First().Author.LoadAuthorPictureAsync();
                                                                                           
                                                                                       };

                                              

                                          };
            
            
            m_account.LoadSitesAsync();            
        }

         [TestMethod] 
         [AsynchronousAttribute]
        public void Assert_Media_Download_OK()
        {

            m_account.SitesLoaded += (o, e) =>
            {
                m_account.PrimarySite.LoadAllPostsAsync();
                m_account.PrimarySite.PostsLoaded += (_, __) =>
                {
                    var post =
                        m_account.PrimarySite.Posts.Where(p => p.Media.Any(media => media.Type == MediumType.Audio)).First();

                    var medium = post.Media.Where(media => media.Type == MediumType.Audio).First();
                    medium.ContentLoaded += (_0, _1) =>
                                                {

                                                    Assert.IsFalse(medium.Content.Length == 0);
                                                    //using (Stream athFileStream = File.Open(MEDIA_PATH, FileMode.Create, FileAccess.Write))
                                                    //{
                                                    //    m_account.PrimarySite.Posts.First().Author.AuthorPicture.CopyToStream(athFileStream);
                                                    //}
                                                    TestComplete();

                                                };
                    
                    medium.LoadContentAsync();

                };



            };


            m_account.LoadSitesAsync();                    
        }


         [TestMethod] 
        [AsynchronousAttribute]
        public void Assert_Exists_Post_In_Site()
        {
            m_account.SitesLoaded += (o, e) =>
            {

                m_account.PrimarySite.PostsLoaded += (_, __) =>
                                                         {
                                                             Assert.IsTrue(m_account.Sites.First().Posts.Count() > 0);
                                                             TestComplete();
                                                           };
                
               m_account.PrimarySite.LoadAllPostsAsync();
            };
            
             m_account.LoadSitesAsync();            
        }

         [TestMethod]
         [AsynchronousAttribute]
        public void Assert_Exists_Post_In_Page1_In_Site()
        {
             m_account.SitesLoaded += (o, e) =>
                                          {
                                              m_account.Sites.First().PostsInPageLoaded += (_, r) =>
                                                                                               {
                                                                                                   Assert.IsTrue(r.Value.Count() == 2);
                                                                                                   TestComplete();
                                                                                               };
                                              m_account.Sites.First().GetPostsInPageAsync(1, 2);

                                          };
            

            m_account.LoadSitesAsync();            

        }

         [TestMethod] 
        [AsynchronousAttribute]
        public void Assert_Exist_Tags_In_Site()
        {
            m_account.SitesLoaded += (o, e) =>
            {
                IPosterousSite site = m_account.PrimarySite;
                site.TagsLoaded += (_, __) =>
                {
                    Assert.IsTrue(site.IsTagsLoaded);
                    TestComplete();
                };
                site.LoadTagsAsync();
            };
            m_account.LoadSitesAsync();            
            

        }

        [TestMethod] 
        [AsynchronousAttribute]
        public void Assert_Exist_Tagged_Posts()
        {

            m_account.SitesLoaded += (o, e) =>
            {
                m_account.Sites.First().PostsByTagLoaded += (_, r) =>
                {
                    Assert.IsTrue(r.Value.Count() > 0);
                    TestComplete();
                };
                
                m_account.Sites.First().GetPostsByTagAsync("Všechno a nic");

            };


            m_account.LoadSitesAsync();                                

        }

         
        [TestMethod] 
        [AsynchronousAttribute]
        public void Assert_Add_Post_Without_Medium()
        {
            m_account.SitesLoaded += (o, e) =>
                                         {
                                             IPosterousSite site = m_account.PrimarySite;
                                             IPosterousPost newPost = site.CreatePost(DateTime.Now + " Příliš žluťoučký kůň úpěl ďábelské ódy",
                                                                                      "Příliš žluťoučký kůň úpěl ďábelské ódy", true);

                                             newPost.AddTag("Všechno a nic");
                                             newPost.AddTag("C# omnia vincit");
                                             newPost.SaveChangesCompleted += (_, __) =>
                                                                                 {
                                                                                     Assert.IsTrue(newPost.Id > 0);
                                                                                     TestComplete();
                                                                                 };
                                             newPost.SaveChangesAsync();


                                         };

            m_account.LoadSitesAsync();    
        }

        [AsynchronousAttribute]
        public void Assert_Add_Post_With_Medium()
        {
            m_account.SitesLoaded += (o, e) =>
            {
                IPosterousSite site = m_account.PrimarySite;
                IPosterousPost newPost = site.CreatePost(DateTime.Now + " Media Silverlight",
                                                         "Příliš žluťoučký kůň úpěl ďábelské ódy", true);

                IsolatedStorageFileStream stream = new IsolatedStorageFileStream("AlbumArtSmall.jpg ", FileMode.Open, IsolatedStorageFile.GetUserStoreForSite());
                newPost.AppendMedium(stream, "mojeSL.jpg", isoStream => isoStream.Close());
                
                //newPost.AppendMedium(fstream, "mojefotka.jpg", stream => stream.Close());

                newPost.AddTag("Všechno a nic");
                newPost.AddTag("C# omnia vincit");
                newPost.SaveChangesCompleted += (_, __) =>
                {
                    Assert.IsTrue(newPost.Id > 0);
                    TestComplete();
                };
                newPost.SaveChangesAsync();


            };

            m_account.LoadSitesAsync();
        }
         
       

        [TestMethod] 
        [AsynchronousAttribute]
        public void Assert_Update_Post_Without_Medium()
        {

            m_account.SitesLoaded += (o, e) =>
                                         {
                                             IPosterousSite site = m_account.PrimarySite;

                                             site.PostsLoaded += (_, __) =>
                                                                     {
                                                                         var post = m_account.Sites.First().Posts.First();

                                                                         string updateText = "Updated " + DateTime.Now.ToString();
                                                                         post.Body = updateText;
                                                                         post.Title = updateText;
                                                                         post.SaveChangesCompleted += (_0, _1) =>
                                                                                                          {
                                                                                                              Assert.IsTrue(post.Id > 0);
                                                                                                              TestComplete();
                                                                                                          };
                                                                         post.SaveChangesAsync();

                                                                     };


                                             site.LoadAllPostsAsync();





                                         };

            m_account.LoadSitesAsync();       
            
                        

        }

        [TestMethod]
        [AsynchronousAttribute]
        public void Assert_Add_Comment_To_Post()
        {


            m_account.SitesLoaded += (o, e) =>
                                         {
                                             IPosterousSite site = m_account.PrimarySite;

                                             site.PostsLoaded += (_, __) =>
                                                                     {
                                                                         var post = site.Posts.Last();

                                                                         string updateText = "Updated " + DateTime.Now.ToString();
                                                                         var comment = post.CreateNewComment(updateText);
                                                                         post.SaveChangesCompleted += (_0, _1) =>
                                                                                                          {
                                                                                                              Assert.IsTrue(comment.Id > 0);
                                                                                                              TestComplete();
                                                                                                          };
                                                                         post.SaveChangesAsync();

                                                                     };


                                             site.LoadAllPostsAsync();





                                         };

            m_account.LoadSitesAsync();       
                        
            

        }

         [TestMethod] 
         [AsynchronousAttribute]
        public void Assert_Exist_BitLY_Post()
        {
             EventHandler<EventArgsValue<ISinglePostInfo>> handler = null;
             handler = (o, e) =>
                           {
                               PosterousApplication.Current.BitLyService.SinglePostLoaded -= handler;
                               Assert.IsNotNull(e.Value);                               
                               TestComplete();
                           };

            PosterousApplication.Current.BitLyService.SinglePostLoaded += handler;
            PosterousApplication.Current.BitLyService.GetSinglePostAsync("Iel3");
            
        }

        [TestMethod] 
        [AsynchronousAttribute]
        public void Assert_Exist_BitLY_Post_MEDIUM()
        {
            EventHandler<EventArgsValue<ISinglePostInfo>> handler = null;
            handler = (o, e) =>
                          {
                              PosterousApplication.Current.BitLyService.SinglePostLoaded -= handler;
                              Assert.IsNotNull(e.Value);
                              e.Value.Media.First().ContentLoaded += (_, __) =>
                                                                         {
                                                                             Assert.IsFalse(e.Value.Media.First().Content.Length == 0);
                                                                             TestComplete();
                                                                         };

                              e.Value.Media.First().LoadContentAsync();


                          };

            PosterousApplication.Current.BitLyService.SinglePostLoaded += handler;

            PosterousApplication.Current.BitLyService.GetSinglePostAsync("Iel3");
            
            
        }

        [TestMethod] 
        [AsynchronousAttribute]
        public void Assert_Add_Twitter_Post_Without_Medium()
        {

            ITwitterPost newPost = m_twitterAccount.CreatePost(DateTime.Now + " Příliš žluťoučký kůň úpěl ďábelské ódy",
                                                               "Příliš žluťoučký kůň úpěl ďábelské ódy", true);

             newPost.SaveChangesCompleted += (o, e) =>
                                                 {
                                                     Assert.IsTrue(newPost.MediaId != String.Empty);
                                                     TestComplete();
                                                 };
            newPost.SaveChangesAsync();
            

        }

        [TestMethod]
        [AsynchronousAttribute]
        public void Assert_Add_Twitter_Post_With_Medium()
        {

            ITwitterPost newPost = m_twitterAccount.CreatePost(DateTime.Now + " Příliš žluťoučký kůň úpěl ďábelské ódy",
                                                               "Příliš žluťoučký kůň úpěl ďábelské ódy", true);

            IsolatedStorageFileStream stream = new IsolatedStorageFileStream("AlbumArtSmall.jpg ", FileMode.Open, IsolatedStorageFile.GetUserStoreForSite());
            newPost.AppendMedium(stream, "mojeSL.jpg", isoStream => isoStream.Close());

            newPost.SaveChangesCompleted += (o, e) =>
            {
                Assert.IsTrue(newPost.MediaId != String.Empty);
                TestComplete();
            };
            
            newPost.SaveChangesAsync();


        }

         [TestMethod] 
        [AsynchronousAttribute]
        public void Assert_Exist_Single_Post_From_Twitter_Post()
        {
            ITwitterPost newPost = m_twitterAccount.CreatePost(DateTime.Now + " Příliš žluťoučký kůň úpěl ďábelské ódy",
                                                              "Příliš žluťoučký kůň úpěl ďábelské ódy", true);

            newPost.SaveChangesCompleted += (o, e) =>
                                                {
                                                    Assert.IsTrue(newPost.MediaId != String.Empty);
                                                    newPost.PostInfoLoaded += (_, result) =>
                                                                                  {
                                                                                      Assert.IsNotNull(result.Value);
                                                                                      TestComplete();
                                                                                  };
                                                    newPost.GetPostInfoAsync();                                                    
                                                };
            newPost.SaveChangesAsync();
            
            

        }
    }
}
